import os
from concurrent.futures import ThreadPoolExecutor
import threading
import time

from conf.settings import JSON_FILE
from interface import init_interface, login_interface, connect_interface, sync_interface, initialization_interface
from interface.init_interface import init_settings, config_dict
from queue import Queue
from lib.common import host_row_search
import logging.config
from conf import settings

logging.config.dictConfig(settings.LOGGING_DIC)  # 导入上面定义的logging配置
logger = logging.getLogger("开始运行")

host_list = list()
host_queue = Queue()
ex_queue = Queue()

BASE_DIR = os.path.dirname(os.path.dirname(JSON_FILE))
NEW_WORKBOOK = os.path.join(BASE_DIR, rf"data\host_{time.strftime('%Y%m%d%H%M%S', time.gmtime())}.xls")


def start_init():
    global NEW_WORKBOOK
    if os.path.exists(NEW_WORKBOOK):
        NEW_WORKBOOK = os.path.join(BASE_DIR, rf"data\host_{time.strftime('%Y%m%d%H%M%S', time.gmtime())}.xls")

    logger.info(" 结果文件  " + NEW_WORKBOOK)

    global host_list
    host_list = init_interface.host_init_interface()
    host_queue.queue.clear()
    ex_queue.queue.clear()


def all_operation(host_queue):
    try:
        # 浏览器初始化
        browser, wait = init_interface.browser_init_interface()
        # 登录
        login_interface.login_interface(browser, wait)
        while True:
            if host_queue.empty():
                break
            host = host_queue.get()
            print(f"\n------------------第{host.host_id}台主机---------------------")

            # 搜索主机
            host_row = host_row_search(browser, host)
            if host_row is None:
                continue
            # 测试连接
            connect_interface.link_test_interface(browser, wait, host_row, host)
            # initialization_interface.initializing_interface(browser, wait, host)
            # 账号查询
            is_exist = sync_interface.account_query_interface(browser, wait, host_row, host)
            if is_exist is None or is_exist is True:
                continue
            # 手工同步
            sync_interface.manual_sync_interface(browser, wait, host)
    except Exception as e:
        logger.error(e)


def only_connect_test(host_queue):
    try:
        # 浏览器初始化
        browser, wait = init_interface.browser_init_interface()
        # 登录
        login_interface.login_interface(browser, wait)

        while True:
            if host_queue.empty():
                break
            host = host_queue.get()
            print(f"\n------------------第{host.host_id}台主机---------------------")
            # 搜索主机
            host_row = host_row_search(browser, host)
            if host_row is None:
                continue
            # 测试连接
            connect_interface.link_test_interface(browser, wait, host_row, host)
    except Exception as e:
        logger.error(e)


def only_initialization(host_queue):
    try:
        # 浏览器初始化
        browser, wait = init_interface.browser_init_interface()
        # 登录
        login_interface.login_interface(browser, wait)
        while True:
            if host_queue.empty():
                break
            host = host_queue.get()
            print(f"\n------------------第{host.host_id}台主机---------------------")
            initialization_interface.only_initializing_interface(browser, host)
    except Exception as e:
        logger.error(e)


def only_manual_sync(host_queue):
    try:
        # 浏览器初始化
        browser, wait = init_interface.browser_init_interface()
        # 登录
        login_interface.login_interface(browser, wait)
        while True:
            if host_queue.empty():
                break
            host = host_queue.get()
            print(f"\n------------------第{host.host_id}台主机---------------------")
            sync_interface.only_manual_sync_interface(browser, wait, host)
    except Exception as e:
        logger.error(e)


def run():
    start_init()
    start_time = time.time()
    init_settings()
    MAX_THREAD = config_dict.get('MAX_THREAD')
    if MAX_THREAD not in [i for i in range(1, 9)]:
        MAX_THREAD = 1
    # MAX_THREAD = 1
    pool = ThreadPoolExecutor(max_workers=MAX_THREAD)
    for host in host_list:
        host_queue.put(host)

    MODE = config_dict.get('MODE')
    func = None
    if MODE == 4:
        print("\n-----只手工同步模式----\n")
        logger.info("-----只手工同步模式----")
        func = only_manual_sync
    elif MODE == 3:
        print("\n-----只初始化模式----\n")
        logger.info("-----只初始化模式----")
        func = only_initialization
    elif MODE == 2:
        print("\n-----只测试连接模式----\n")
        logger.info("-----只测试连接模式----")
        func = only_connect_test
    else:
        print("\n-----全功能模式----\n")
        logger.info("-----全功能模式----")
        func = all_operation

    future_list = list()
    for i in range(MAX_THREAD):
        future_list.append(pool.submit(func, host_queue=host_queue))

    if MAX_THREAD == 1:
        while True:
            if future_list[0].done():
                break
    else:
        while True:
            flag = True
            for future in future_list:
                if not future.done():
                    flag = False
                    break
            if flag:
                break

            # if future_list[0].done() and future_list[1].done() and future_list[2].done():
            #     break

    end_time = time.time()
    print(f"\n本次运行耗时{end_time - start_time}秒")
    # input("运行完成 请于 data目录 下的最新文件中查看结果 \n按回车键关闭程序")


if __name__ == "__main__":
    try:
        run()
    except Exception as e:
        logger.error(e)
